from django.template import Library, Node, Variable
from django.template.loader import render_to_string

from hdg.djangoapps.simplecms.models import Navigation


register = Library()

class LangMenu(Node):
    def __init__(self,store_to_variable_name, uplink):
        self.store_to_variable_name = store_to_variable_name
        self.uplink = uplink

    def render(self, context):
        var_name = Variable(self.store_to_variable_name).resolve(context)
        if self.uplink:
            uplink = Variable(self.uplink).resolve(context)
        else:
            uplink = self.uplink
        try:
            objects_list = Navigation.objects.filter(uplink__short_title=uplink).order_by('sort_order')
        except TextBlock.DoesNotExist:
            return ''
        context[var_name]=objects_list
        return ''

def get_lang_menu(parser, token):
    """
    {% get_lang_menu <store_to_variable_name> <lang> %}
    """
    arr = token.split_contents()
    store_to_variable_name = arr[1]
    if len(arr) == 2:
        uplink = None
    else:
        uplink = arr[2]
    return LangMenu(store_to_variable_name, uplink)


register.tag('get_lang_menu', get_lang_menu)

from hdg.djangoapps.news.models import NewsArticle

@register.inclusion_tag('news/news_box.html', takes_context=True)
def news_box(context,lang,howmany=None):
    articles = NewsArticle.objects.filter(language=lang).order_by('-pub_date')
    if howmany:
        articles = articles[:howmany]
    
    context['articles']=articles
    context['lang']=lang
    print 1
    return context
